package DAL;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import entities.ConnectionManager;
import entities.User;

public class UserDA {
	public User[] selectUsers(User user)
	{
		String query = "SELECT * from [User]  " ;
		if(user.getUserID() != -1)
		{
			query += "WHERE userid = " + user.getUserID();
			if(!user.getEmail().equals("")) query += " AND email = '" + user.getEmail() + "'";
		}
		else
			if(!user.getEmail().equals("")) query += " WHERE email = '" + user.getEmail() + "'";

		ConnectionManager con = new ConnectionManager();
		ResultSet rs = con.executeSelectQuery(query);
		
		ArrayList<User> users = new ArrayList<User>();

		
		try {
			while(rs.next())
			{
				User tempUser= new User();
				tempUser.setUserID(rs.getInt("userid"));
				tempUser.setEmail(rs.getString("email"));
				users.add(tempUser);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		User [] temp = new User [0];
		return users.toArray(temp);

	}


	public boolean updateUser(User user)
	{
		String query = "UPDATE [User] SET email = '" + user.getEmail() +
				"' WHERE userid = "+ user.getUserID();
		
		ConnectionManager con = new ConnectionManager();
		
		int x = con.executeUpdateQuery(query);
		
		return (x==1);
	}
	
	public boolean insertUser(User user)
	{
		String query = "INSERT INTO [User] (email) VALUES " +
				"('" + user.getEmail() + "')";
		
		ConnectionManager con = new ConnectionManager();
		
		int x = con.executeUpdateQuery(query);
		
		return x==1;
	}
	
	public int deleteUser(User user)
	{
		String query = "DELETE FROM [User] ";
		if(user.getUserID() != -1)
		{
			query += "WHERE userid = " + user.getUserID();
			if(!user.getEmail().equals("")) query += " AND email = '" + user.getEmail() + "'";
		}
		else
			if(!user.getEmail().equals("")) query += " WHERE email = '" + user.getEmail() + "'";
		
		ConnectionManager con = new ConnectionManager();
		
		int x = con.executeUpdateQuery(query);
		
		return x;
	}
	
	
	public static void main(String[] args) {
		User u = new User();

		//u.setUserID(3);
		u.setEmail("asdadasssfdaad");
		
		UserDA da = new UserDA();
		System.out.println(da.deleteUser(u));
	}

}
